<template>
  <div class="info_main mt-5 ml-5">
    <!--    搜素框  -->
    <div class="row" >
      <div class="col-md-2">
        <!--        <el-button @click="toggleSelection()">取消选择</el-button>-->
        <el-select v-model="fiter_check" placeholder="选择审核情况..." @change="changecheck">
          <el-option label="审核通过" value="1"></el-option>
          <el-option label="审核不通过" value="2"></el-option>
          <el-option label="未审核" value="0"></el-option>
        </el-select>
      </div>
      <div class="col-md-8">
        <el-input  type="text"
                   v-model="findName"
                   style="width: 500px;"
                   placeholder="请输入用户名..."
                   clearable
                   @keyup.enter.native="searchByName">
        </el-input>
        <el-button type="primary" icon="el-icon-search" @click="searchByName()" class="ml-3" plain>搜索</el-button>
        <el-button type="info" icon="el-icon-delete" @click="clearFindInput()" class="ml-3">重置</el-button>
      </div>
    </div>
    <!--      批量删除按钮-->
    <div class="mt-3">
      <!--      添加按钮-->
      <el-button type="primary" @click="addOpen()" plain><i class="el-icon-plus" ></i>创建</el-button>
      <el-button @click="toggleSelection()">取消选择</el-button>
      <el-button type="danger" @click="handleMultipleDelete">批量删除</el-button>
    </div>
    <div class="show_data mt-4">
      <el-table
          ref="multipleTable"
          v-horizontal-scroll="'always'"
          show-overflow-tooltip
          :data="showData"
          style="width: 100%"
          :cell-style="{color: '#666', fontFamily: 'Arial',fontSize:'17px'}"
          :header-cell-style="{background:'whitesmoke', fontFamily:'Helvetica',fontSize:'20px'}"
          height="700"
          @selection-change="handleSelectionChange"
          tooltip-effect="dark"
          :default-sort = "{prop: 'date', order: 'descending'}">
        <el-table-column
            type="selection"
            width="60">
        </el-table-column>
        <el-table-column
            fixed
            prop="register_time"
            label="注册时间"
            width="260">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.register_time }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="ifcheck"
            label="审核情况"
            width="160"
            column-key="ifcheck">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.ifcheck==1" disable-transitions type="success">
              <span class="typeClass">审核通过</span>
            </el-tag>
            <el-tag v-else-if="scope.row.ifcheck==2" disable-transitions type="danger">
              <span class="typeClass">审核不通过</span>
            </el-tag>
            <el-tag v-else-if="scope.row.ifcheck==0" disable-transitions type="primary">
              <span class="typeClass">未审核</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="identity"
            label="身份"
            width="160">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.identity==1" disable-transitions type="success">
              <span class="typeClass">学长学姐</span>
            </el-tag>
            <el-tag v-else-if="scope.row.identity==2" disable-transitions type="danger">
              <span class="typeClass">老师</span>
            </el-tag>
            <el-tag v-else-if="scope.row.identity==0" disable-transitions type="primary">
              <span class="typeClass">学生</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="user_name"
            label="用户名"
            width="160">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="手机号"
            width="160">
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="250">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="edit(scope.$index, scope.row)">
              <span class="btnfontClass" >修改</span>
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">
              <span class="btnfontClass" >删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--    分页-->
      <div class="pagin mt-5 mb-5">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page="userContainerPage"
            :page-size="userContainerSize"
            layout="total,prev, pager, next"
            :total=total>
        </el-pagination>
      </div>

      <!--编辑弹窗-->
      <el-dialog
          title="编辑用户账户信息"
          :visible.sync="editdialogVisible"
          width="45%"
          @close="handleCloseEdit">

        <!--        编辑表单-->
        <el-form ref="PersonAccount" :model="PersonAccount" label-width="100px" :before-close="closeDivEdit">

          <form>

            <div class="form-group">
              <label for="inputPhone">手机号</label>
              <input type="phone" class="form-control" id="inputPhone" v-model="PersonAccount.phone" >
              <small id="phoneHelpBlock" class="form-text text-muted">
                手机号不可重复注册！
              </small>
            </div>
<!--            <div class="form-group">-->
<!--              <label for="inputPassword">旧密码</label>-->
<!--              <input type="password" class="form-control" id="inputPassword" placeholder="请输入旧密码"  v-model="PersonAccount.old_pwd">-->
<!--            </div>-->
            <div class="form-group">
              <label for="inputNewPassword">新密码</label>
              <input type="password" class="form-control" id="inputNewPassword" placeholder="请输入新密码"  v-model="PersonAccount.new_pwd">
              <small id="passwordHelpBlock1" class="form-text text-muted">
                （密码至少包含数字和英文，长度6-20）
              </small>
            </div>
            <div class="form-group">
              <label for="inputNewPassword1">确认密码</label>
              <input type="password" class="form-control" id="inputNewPassword1" placeholder="再次输入"  v-model="PersonAccount.new_pwd_again">
            </div>
          </form>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="editSave()">修 改</el-button>
          <el-button @click="openCancelEdit">取 消</el-button>
        </span>
      </el-dialog>

      <!--添加弹窗-->
      <el-dialog
          title="创建用户"
          :visible.sync="addialogVisible"
          width="40%"
          @close="handleClose">

        <!--       添加表单-->
        <el-form ref="Addform" :model="Addform" label-width="100px" :before-close="closeDiv">

          <el-form-item label="身份：" :label-width="formLabelWidth" prop="identity" required>
            <el-select v-model="Addform.identity" placeholder="请选择身份...">
              <el-option label="学生" value="0" name="学生"></el-option>
              <el-option label="学长学姐" value="1" name="学长学姐"></el-option>
              <el-option label="老师" value="2" name="老师"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="手机号：" :label-width="formLabelWidth" prop="phone" required>
            <el-input
                placeholder="请输入手机号"
                show-word-limit
                v-model="Addform.phone"
                type="text">
            </el-input>
          </el-form-item>

          <el-form-item label="用户名：" :label-width="formLabelWidth" prop="username" required>
            <el-input
                placeholder="请输入用户名"
                show-word-limit
                v-model="Addform.username"
                type="text">
            </el-input>
          </el-form-item>

          <el-form-item label="密码：" :label-width="formLabelWidth" prop="pwd" required>
            <el-input
                placeholder="请输入密码"
                show-word-limit
                type="password"
                maxlength="20"
                v-model="Addform.pwd"></el-input>
            <small id="pwdHelp" class="form-text text-muted">（密码至少包含数字和英文，长度6-20）</small>
          </el-form-item>

          <el-form-item label="确认密码：" :label-width="formLabelWidth" prop="pwdAgain" required>
            <el-input
                placeholder="请再次输入密码"
                show-word-limit
                type="password"
                maxlength="20"
                v-model="Addform.pwdAgain"></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAdd('Addform')">添 加</el-button>
          <el-button @click="cancel">取 消</el-button>
          <el-button @click="clearInput('Addform')">重 置</el-button>
        </span>
      </el-dialog>


    </div>
  </div>
</template>

<script>
import {deleteUserByUserID, getAllUserInfo, updateUserAccountByAdmin, register, deleteMutipleUser} from "@/api/User";

export default {
  name: "information_main",
  data() {
    return {
      //筛选相关
      fiter_check:'',
      //搜索相关功能
      findName:'',
      userContainerPage:0, // 分页的数据：当前页数
      userContainerSize:0, // 分页的数据：每页的数量
      total:0,
      UserData: [],
      showData:[],
      copyData:[],
      search_info:[],  //存放搜索到的容器
      multipleSelection: [],
      //  编辑功能相关
      editdialogVisible:false,
      PersonAccount:{
        user_id:'',
        phone:'',
        new_pwd:'',
        new_pwd_again:'',

      },
      formLabelWidth: '100px',
      //  添加弹窗相关
      addialogVisible:false,
      Addform:{
        phone:'',
        pwd:'',
        pwdAgain:'',
        identity:'',
        username:''

      },





    }
  },

  methods: {
    //获取全部用户个人基本信息
    init(){

      getAllUserInfo({}).then(res=>{
        this.UserData=res.data;
        this.copyData=res.data;
        this.getShowUser();
      })

    },
    getShowUser(){

      this.userContainerSize=parseInt(10);
      this.showData = this.UserData.slice((this.userContainerPage - 1) * this.userContainerSize, this.userContainerPage * this.userContainerSize);
      this.total=parseInt(this.UserData.length);

    },
    //根据管理员名进行搜索
    searchByName(){

      var search=this.findName;
      if(search==""||search==null)
      {
        this.$msg.error('输入框不能为空！');
        this.init();
      }
      else {
        //执行本地过滤
        var search_list=this.copyData;
        this.search_info=[];  //装搜索结果的容器
        for(let i=0;i<search_list.length;i++)
        {
          if(search_list[i].user_name.indexOf(search)>=0)
          {
            this.search_info.push(search_list[i]);
          }
        }
        if(this.search_info.length==0)
        {
          this.$msg.error('未找到相关结果,刷新一下~');
        }
        this.UserData=this.search_info;
        //分页
        this.userContainerPage=parseInt(1);
        this.getShowUser();

        //清空搜索框
        this.findName="";
      }

    },
    //  数据筛选
    changecheck(){

      var search=this.fiter_check;
      //执行本地过滤
      var search_list=this.copyData;
      this.search_info=[];  //装搜索结果的容器
      for(let i=0;i<search_list.length;i++)
      {
        if(search_list[i].ifcheck==search)
        {
          this.search_info.push(search_list[i]);
        }
      }
      if(this.search_info.length==0)
      {
        this.$msg.error('未找到相关结果,刷新一下~');
      }
      this.UserData=this.search_info;
      //分页
      this.userContainerPage=parseInt(1);
      this.getShowUser();


    },
    //分页
    //page改变时的回调函数，参数为当前页码
    handleCurrentChange(val) {

      console.log(`当前页: ${val}`);
      this.userContainerPage= parseInt(val);
      this.getShowUser();

    },
    //编辑管理员信息  打开编辑弹窗
    edit(index, row) {

      this.editdialogVisible=true;

      this.PersonAccount.user_id=row.user_id;
      this.PersonAccount.phone=row.phone;


    },
    //提交数据 修改
    editSave()
    {

      //再次确认
      this.$confirm('确认修改?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.updateSave();

      }).catch(() => {
        this.$msg.error("修改失败！");
      });

    },
    //连接后端  进行修改
    updateSave(){

      var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;   //合法的手机号
      var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/; //密码至少包含 数字和英文，长度6-20

      if(this.PersonAccount.phone.length==0){
        this.$msg.warning('手机号不能为空！');
        return false;
      }
      if(!myreg.test(this.PersonAccount.phone))
      {
        this.$msg.warning('手机号不合法，请重新输入！');
        return false;
      }
      if(this.PersonAccount.new_pwd.length==0){
        this.$msg.warning('请输入新密码！');
        return false;
      }
      if(!reg.test(this.PersonAccount.new_pwd))
      {
        this.$msg.warning('密码至少包含数字和英文，长度为6-20！');
        return false;
      }
      if(this.PersonAccount.new_pwd_again.length==0){
        this.$msg.warning('请再次输入新密码！');
        return false;
      }
      if(this.PersonAccount.new_pwd!=this.PersonAccount.new_pwd_again){
        this.$msg.warning('两次输入的密码不一致，请重新输入！');
        this.PersonAccount.new_pwd="";
        this.PersonAccount.new_pwd_again="";
        return false;
      }
      updateUserAccountByAdmin({
        user_id:this.PersonAccount.user_id,
        phone:this.PersonAccount.phone,
        new_pwd:this.PersonAccount.new_pwd
      }).then(res=>{
        if(res.data.result==1){
          this.$msg.success('修改成功！');
          this.editdialogVisible=false;
          this.init();
        }
        else if(res.data.result == -1){
          this.$msg.warning('手机号已存在，请勿重复！')
        }
        else if(res.data.result == 0){
          this.$msg.error('修改失败！');
        }
      })


    },
    //删除
    handleDelete(index, row) {

      //再次确认
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.deleteSave(row.user_id);

      }).catch(() => {
        this.$msg.error("取消删除！");
      });

    },
    //连接后端，进行删除
    async deleteSave(user_id){
      deleteUserByUserID({
        user_id:user_id
      }).then(res=>{
        if(res.data.code==1){
          this.$msg.success("删除成功！");
        }else{
          this.$msg.error("删除失败！");
        }
        this.init();
      })

    },
    //  关闭弹窗
    openCancelEdit(){
      this.editdialogVisible = false
      // 点击取消按钮的时候清除输入框中的内容 清除验证
      //  this.$nextTick获取了节点之后进行操作
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["PersonAccount"].resetFields();
      });
    },
    // 右上角 × 取消按钮
    closeDivEdit(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["PersonAccount"].resetFields();
      });
    },
    //清空搜索框
    clearFindInput(){
      this.findName="";
      this.fiter_check="";
      this.init();
    },
    handleCloseEdit(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["PersonAccount"].resetFields();
      });
    },
    //打开添加的弹窗
    addOpen(){
      this.addialogVisible=true;
    },
    submitAdd(formName){

      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //再次确认
          this.$confirm('确认创建?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.addSave();

          }).catch(() => {
            this.$msg.error("创建失败！");
          });

        }
        else {
          this.$msg.error("创建失败！");
          return false;
        }
      });

    },
    //连接后端 创建用户
    addSave(){

      var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;   //合法的手机号
      var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/; //密码至少包含 数字和英文，长度6-20
      if(this.Addform.identity === -1)
      {
        this.$msg.warning('请选择身份！')
      }
      else if(this.Addform.username<=0)
      {
        this.$msg.warning('请输入用户名！')
      }
      else if(this.Addform.phone<=0)
      {
        this.$msg.warning('请输入手机号！')
      }
      else if(!myreg.test(this.Addform.phone))
      {
        this.$msg.warning('手机号不合法，请重新输入！')
      }
      else if(this.Addform.pwd<=0)
      {
        this.$msg.warning('请输入密码！')
      }
      else if(!reg.test(this.Addform.pwd))
      {
        this.$msg.warning('密码至少包含数字和英文，长度为6-20！');
        this.Addform.pwd="";
        this.Addform.pwdAgain="";
      }
      else if(this.Addform.pwdAgain<=0)
      {
        this.$msg.warning('请再次输入密码！')
      }
      else if(this.Addform.pwd!==this.Addform.pwdAgain)
      {
        this.$msg.warning('两次输入的密码不一致，请重新输入！');
        this.Addform.pwd="";
        this.Addform.pwdAgain="";
      }
      else
      {

        register({
          phone:this.Addform.phone,
          pwd:this.Addform.pwd,
          identity:this.Addform.identity,
          username:this.Addform.username
        }).then(res=>{
          if(res.data.result===1){
            this.$msg.success('添加成功！');
            this.addialogVisible=false;
            this.init();
          }
          else if(res.data.result=== -1){
            this.$msg.error('手机号已存在，请勿重复注册！');

          }
          else if(res.data.result=== 0){
            this.$msg.error('用户名已存在，请勿重复！');
            this.Addform.username='';
          }
          else{
            this.$msg.error('添加失败！');
          }
        })

      }


    },
    //  关闭弹窗
    cancel() {
      this.addialogVisible = false
      // 点击取消按钮的时候清除输入框中的内容 清除验证
      //  this.$nextTick获取了节点之后进行操作
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });

    },
    handleClose(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });
    },
    // 右上角 × 取消按钮
    closeDiv() {

      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });

    },
    //重置按钮
    clearInput(formName){
      this.$refs[formName].resetFields();
    },
    //取消选择
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //  批量删除
    handleMultipleDelete(){

      if (this.multipleSelection == '') {
        this.$message.error('您未选中任何用户，请重新操作！！！');
        return;
      }

      let checkArr = this.multipleSelection;  // multipleSelection存储了勾选到的数据
      let user_ids = [];
      checkArr.forEach(function (item) {
        user_ids.push(item.user_id);
      });

      //再次确认
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        deleteMutipleUser({
          user_id:user_ids,
        }).then(res=>{
          if(res.data.code==1){
            this.$msg.success("批量删除成功！");
          }else{
            this.$msg.error("删除失败！");
          }
          this.init();
        });

      }).catch(() => {
        this.$msg.error("取消删除！");
      });


    },



  },
  created() {
    let _this=this;
    _this.userContainerPage=parseInt(1);
    _this.init();
    _this.$refs.table.doLayout();
  },
}
</script>

<style scoped>
.btnfontClass{
  font-size: 15px;
}
.el-pagination {
  text-align: center;
}
.typeClass{
  font-size: 14px;
}
/*表格展开功能样式*/
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
